package utils

import (
	"fmt"
	"math/rand"
	"os"
	"runtime/debug"
	"time"
)

func SafeCall(callback func(args ...interface{}) error, iargs ...interface{}) error {
	defer func() {
		if err := recover(); err != nil {
			rand := rand.New(rand.NewSource(time.Now().UnixNano()))
			rvalue := rand.Intn(100000000)
			now := time.Now()
			filename := fmt.Sprintf("dianwancheng[%d%02d%02d%02d%02d%02d%d]_%d.dump", now.Year(), now.Month(), now.Day(), now.Hour(), now.Minute(),
				now.Second(), now.Nanosecond(), rvalue)

			var f *os.File

			if IsExist(filename) {
				f, _ = os.OpenFile(filename, os.O_APPEND, 0666)
			} else {
				f, _ = os.Create(filename)
			}

			defer f.Close()
			f.Write([]byte(err.(error).Error()))
			f.Write(debug.Stack())
		}
	}()

	return callback(iargs...)
}
